package dq.study.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.apache.shiro.web.servlet.ShiroFilter;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @author dongqun
 * @date 2020/4/10 10:26
 */
public class UsernamePasswordRealm extends AuthorizingRealm {

    private PasswordService passwordService;

    public void setPasswordService(PasswordService passwordService) {
        this.passwordService = passwordService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        List<String> usernames = principals.asList();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<Permission> permissions = new HashSet<>();
        if (usernames.contains("zhangsan")) {
            permissions.add(new WildcardPermission("system:auth:*"));
            permissions.add(new WildcardPermission("system:user:*"));
        }
        authorizationInfo.setObjectPermissions(permissions);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = (String) usernamePasswordToken.getUsername();
        String password = (String) new String(usernamePasswordToken.getPassword());
        if (!username.equals("zhangsan")) {
            throw new UnknownAccountException();
        }
        if (!password.equals("123")) {
            throw new IncorrectCredentialsException();
        }
        String cipherText = new Md5Hash("123", "232132131423EWQEQWEQ", 2).toString();
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, cipherText, getName());
        authenticationInfo.setCredentialsSalt(new SimpleByteSource("232132131423EWQEQWEQ"));
        return authenticationInfo;
    }
}
